package com.cpms.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cpms.config.jwt.JwtUtils;
import com.cpms.utils.ResultUtils;
import com.cpms.utils.ResultVo;
import com.cpms.web.entity.User;
import com.cpms.web.entity.UserInfo;
import com.cpms.web.entity.param.LoginParm;
import com.cpms.web.entity.param.LoginResult;
import com.cpms.web.entity.param.UserParm;
import com.cpms.web.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 员工管理层
 * */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginParm parm){
        if (StringUtils.isEmpty(parm.getLoginName()) || StringUtils.isEmpty(parm.getPassword()) || StringUtils.isEmpty(parm.getUserType())){
            return ResultUtils.error("用户名、密码或者用户类型不能为空!");
        }
        //加密前端传递密码
        String password = DigestUtils.md5DigestAsHex(parm.getPassword().getBytes());
        //构造查询条件
        QueryWrapper<User> query = new QueryWrapper<>();
        query.lambda().eq(User::getLoginName,parm.getLoginName())
                .eq(User::getPassword,password);
//        userType（用户类型）还未使用
        User user = userService.getOne(query);
        //未在数据库中查找到该用户
        if(user == null){
            return ResultUtils.error("用户名、密码或者用户类型错误！");
        }
        //生成的token返回给前端
        String token = jwtUtils.generateToken(user.getLoginName());
        //获取token过期时间
        Long time = jwtUtils.getExpireTime(token);
        LoginResult result = new LoginResult();
        result.setUserId(user.getUserId());
        result.setToken(token);
        result.setExpireTime(time);
        return ResultUtils.success("登录成功！",result);
    }


    @GetMapping("/getInfo")
    public ResultVo getInfo(User user){
        //获取用户id
        User user1 = userService.getById(user.getUserId());
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user1.getUserId());
        userInfo.setName(user1.getUserName());
        userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        return ResultUtils.success("获取用户信息成功",userInfo);
    }

    /**
     * 查询员工列表
     * @param parm
     * @return
     */
    @GetMapping("/list")
    public ResultVo list(UserParm parm){
        IPage<User> list = userService.list(parm);
        //前端不展示密码
        list.getRecords().stream().forEach(item -> item.setPassword(""));
        return ResultUtils.success("查询成功",list);
    }

    /**
     * 新增员工
     * @param user
     */
    @PostMapping
    public ResultVo addUser(@RequestBody User user){
        //判断登录名是否唯一
        if (StringUtils.isNotEmpty(user.getLoginName())){
            QueryWrapper<User> query = new QueryWrapper<>();
            query.lambda().eq(User::getLoginName,user.getLoginName());
            User one = userService.getOne(query);
            if (one != null && one.getUserId() != user.getUserId()){
                return ResultUtils.error("登录名已经被占用！",500);
            }
        }
        //密码存在，ND5加密
        if (StringUtils.isNotEmpty(user.getPassword())){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        boolean save = userService.save(user);
        if(save){
            return ResultUtils.success("新增员工成功!");
        }
        return ResultUtils.error("新增员工失败！");
    }

    /**
     * 编辑员工信息
     * @param user
     */
    @PutMapping
    public ResultVo edditUser(@RequestBody User user){
        //判断登录名是否唯一
        if (StringUtils.isNotEmpty(user.getLoginName())){
            QueryWrapper<User> query = new QueryWrapper<>();
            query.lambda().eq(User::getLoginName,user.getLoginName());
            User one = userService.getOne(query);
            if (one != null && one.getUserId() != user.getUserId()){
                return ResultUtils.error("登录名已经被占用！",500);
            }
        }
        //密码存在，ND5加密
        if (StringUtils.isNotEmpty(user.getPassword())){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        boolean edit = userService.updateById(user);
        if(edit){
            return ResultUtils.success("编辑员工成功!");
        }
        return ResultUtils.error("编辑员工失败！");
    }

    /**
     * 删除员工
     * @param userId
     */
    @DeleteMapping("/{userId}")
    public ResultVo deleteUser(@PathVariable("userId") Long userId){
        boolean delete = userService.removeById(userId);
        if(delete){
            return ResultUtils.success("删除员工成功!");
        }
        return ResultUtils.error("删除员工失败！");
    }

}